package com.hanbang.chu_xing_gao_zhao.view_find_esoterica;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.entity.CommentData;
import com.hanbang.chu_xing_gao_zhao.entity.FindEsotericaDataK;
import com.hanbang.chu_xing_gao_zhao.myview.MorePopupWindowPublic_B;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.chu_xing_gao_zhao.view_pay.EsotericaPayActivity;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 开发放式秘籍付款前的页面
 */
public class FindEsotericaDetails_K_PayFront extends BaseActivity {
    /**
     * 瀑布流控件
     */
    private RecyclerView mRecyclerView;
    /**
     * 瀑布流适配器
     */
    private MyRecyclerViewAdapterB adapter;
    /**
     * 瀑布流数据集合
     */
    private List<FindEsotericaDataK> listData = new ArrayList<FindEsotericaDataK>();

    /**
     * 视频图片
     */
    private ImageView videoPicture;

    /**
     * 请求参数
     */
    private RequestParams params;
    /**
     * 视频的路径
     */
    public String urlV = "";
    private TextView affirmPay;

    /**
     * 秘籍Id
     */
    private int esotericaId;
    /**
     * 标示名字
     */
    private String name;

    /**
     * 评论列表
     */
    private ArrayList<CommentData> commentData = new ArrayList<CommentData>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_esoterica_deteils_k);
        initView();
        recyclerAddLinear();
        setOnClickListener();

        getHttpCommentList();


    }

    /**
     * 初始化view
     */
    private void initView() {
        Intent intent = getIntent();

        //标题设置
        name = intent.getStringExtra("name");
        esotericaId = intent.getIntExtra("id", -1);
        setTitleMore(View.VISIBLE, View.INVISIBLE, name, null, null, null);
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));
        mRecyclerView = (RecyclerView) this.findViewById(R.id.rv_find_esotarica_details);
        affirmPay = (TextView) findViewById(R.id.tv_find_esoterica_deteils_k_affirmPay);

        //调用接口
        params = new RequestParams();
        params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                this, MySharedPreferences.USER_DATA, "tlephone"));
        params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                this, MySharedPreferences.USER_DATA, "password"));
        params.addBodyParameter("id", esotericaId + "");
        getHttpDetails(HttpInterfaces.Miji_Show, params, esotericaId);


    }

    /**
     * recyclerView 添加适配器 与添加监听
     */
    private void recyclerAddLinear() {
        listData.add(new FindEsotericaDataK());
        listData.add(new FindEsotericaDataK());
        listData.add(new FindEsotericaDataK());
        listData.add(new FindEsotericaDataK());
        listData.add(new FindEsotericaDataK());
        listData.add(new FindEsotericaDataK());

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        /**
         * 第一个参数，是控件列数或行数，第二参数是控制方向
         *  设置RecyclerView布局管理器为2列垂直排布
         */
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));// 设置RecyclerView布局管理器为2列垂直排布

        adapter = new MyRecyclerViewAdapterB(listData);

        mRecyclerView.setAdapter(adapter);

        adapter.setOnClickListener(new OnItemClickListener() {

            //跳转到详情界面
            public void ItemClickListener(View view, int postion) {
//
            }


            public void ItemLongClickListener(View view, int postion) {
//                listData.remove(postion);
//                adapter.notifyItemRemoved(postion);
            }
        });
    }


    /**
     * 设置点击事件
     */

    private void setOnClickListener() {
        affirmPay.setOnClickListener(onClickListener);

    }

    /**
     * 处理监听
     */
    @SuppressWarnings("unused")
    private OnClickListener onClickListener = new OnClickListener() {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            switch (v.getId()) {

                //临时跳转付款后
                case R.id.tv_find_esoterica_deteils_k_affirmPay:
                    intent.setClass(FindEsotericaDetails_K_PayFront.this, EsotericaPayActivity.class);

                    startActivity(intent);
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }


    private void getHttpDetails(String url, RequestParams params, int id) {
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new MyRequestCallBack<String>(this, "加载中...") {


            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);
                    boolean request = json.getBoolean("Result");

                    if (request) {
                        JSONObject data = json.getJSONObject("model");


                        ((TextView) findViewById(R.id.tv_find_esoterica_details_head_k_pay_front_name)).setText(data.get("title").toString());
                        ((TextView) findViewById(R.id.tv_find_esoterica_details_head_k_pay_front_miCheng)).setText(data.get("tedian").toString());
                        ((TextView) findViewById(R.id.tv_find_esoterica_details_head_k_pay_front_xueFei)).setText("学费" + String.valueOf(data.getDouble("price") + "元"));
                        ((TextView) findViewById(R.id.tv_find_esoterica_details_head_k_pay_front_jianJie)).setText("简介：" + data.get("jianjie").toString());

                        //显示图片
                        bitmapUtils.display(((ImageView) findViewById(R.id.iv_find_esoterica_details_head_k_pay_front_picture)), SystemTools.getHttpFileUrl(data.get("img_url").toString()));

                        //如果有视频则显示图片，没有则隐藏
                        if (data.get("liuchengshipin").toString().contains(".mp4")) {
                            ((ImageView) findViewById(R.id.iv_find_esoterica_details_head_k_pay_front_video)).setVisibility(View.VISIBLE);
                            ((ImageView) findViewById(R.id.iv_find_esoterica_details_head_k_pay_front_video)).setImageResource(R.drawable.default_play);
                        }

                        urlV = data.getString("liuchengshipin");

                        ((TextView) findViewById(R.id.tv_find_esoterica_details_head_k_pay_front_xiaoLiang)).setText("销量：" + data.get("buycount").toString());
                        ((TextView) findViewById(R.id.tv_find_esoterica_details_head_k_pay_front_pingFeng)).setText("评分：" + data.get("pingfen").toString());
                        ((TextView) findViewById(R.id.tv_find_esoterica_details_head_k_pay_front_pingLun)).setText("评论：" + data.get("pingjia").toString());


                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }


            }
        });


    }


    /**
     * 适配器
     */
    public class MyRecyclerViewAdapterB extends RecyclerView.Adapter<MyViewHolderB> implements View.OnClickListener {
        /**
         * 数据
         */
        private List<FindEsotericaDataK> lists;
        private OnItemClickListener mListener;

        // view的type：头部，内容，加载更多
        private static final int TYPE_HEADER = 1, TYPE_ITEM = 2;


        public MyRecyclerViewAdapterB(List<FindEsotericaDataK> lists) {


            if (lists != null) {
                this.lists = lists;

            } else {
                this.lists = new ArrayList<FindEsotericaDataK>();
            }

        }


        @Override
        public void onClick(View v) {

            Intent intent = new Intent();
            MorePopupWindowPublic_B popup = null;
            switch (v.getId()) {

                //临时跳转到付费后
                case R.id.iv_find_esoterica_details_head_k_pay_front_video:
                    intent.setClass(FindEsotericaDetails_K_PayFront.this, EsotericaPayActivity.class);
                    startActivity(intent);
                    break;

            }


        }

        public void setOnClickListener(OnItemClickListener listener) {
            this.mListener = listener;
        }

        @Override
        public MyViewHolderB onCreateViewHolder(ViewGroup parent, int viewType) {
//            MyLog.i("text", "AAA onCreateViewHolder*****" );
            View view = null;
            // 根据类型填充不同布局
            switch (viewType) {
                //添加头部
                case TYPE_HEADER:
                    view = getLayoutInflater().inflate(R.layout.find_esoterica_details_head_k_pay_front, parent, false);
                    videoPicture = (ImageView) view.findViewById(R.id.iv_find_esoterica_details_head_k_pay_front_video);
                    videoPicture.setOnClickListener(this);
                    break;
                //内容
                case TYPE_ITEM:
                    view = getLayoutInflater().inflate(R.layout.item_find_esoterica_k, parent, false);
                    break;


            }

            //更改字体
            UiUtils.applyFont(view);
            MyViewHolderB viewHolder = new MyViewHolderB(view);
            return viewHolder;
        }


        @Override
        public void onBindViewHolder(final MyViewHolderB holder, int position) {
            switch (holder.getItemViewType()) {
                //使用头单独占一行
                case TYPE_HEADER:
                    // 最最关键一步，设置当前view占满列数，这样就可以占据两列实现头部了
                    StaggeredGridLayoutManager.LayoutParams clp = (StaggeredGridLayoutManager.LayoutParams) holder.head.getLayoutParams();
                    /**
                     * 如果设置为true，该项目将布局采用全量程范围。这意味着，如果方向
                      *是垂直的，认为将有充分的宽度;如果方向是水平的，视图将
                      *有充分的高度。
                       *参数fullSpan如果此项目应遍历所有的跨度。
                     */
                    clp.setFullSpan(true);

                    break;
                //内容的展示
                case TYPE_ITEM:
                    if (lists.size() == 0 || lists.size() < position) {
                        return;
                    }
                    //因为传过来的position是从0开始，所以要减1.
                    position = position - 1;
                    ViewGroup.LayoutParams params = holder.itemView.getLayoutParams();// 得到item的LayoutParams布局参数
                    holder.itemView.setLayoutParams(params);// 把params设置给item布局

//                    MyLog.i("text", "CCC lists.size*****" + lists.size() + "position" + position);

                    bitmapUtils.configDefaultLoadFailedImage(R.drawable.default_white);

                    bitmapUtils.display(holder.picture, SystemTools.getHttpFileUrl(lists.get(position).getImg_url()));


                    holder.craft.setText(lists.get(position).getTitle());
                    holder.price.setText("¥" + String.valueOf(lists.get(position).getPrice()));
                    holder.browse.setText("菜品特色:" + lists.get(position).getTedian());
                    holder.feature.setText("销量：" + lists.get(position).getBuycount());
                    holder.pingFen.setText("评分：" + lists.get(position).getPingfen());

                    //设置item 的监听
                    if (mListener != null) {// 如果设置了监听那么它就不为空，然后回调相应的方法
                        /**
                         * 点击监听
                         */
                        holder.itemView.setOnClickListener(new View.OnClickListener() {

                            public void onClick(View v) {
                                int pos = holder.getPosition();// 得到当前点击item的位置pos
                                mListener.ItemClickListener(holder.itemView, pos);// 把事件交给我们实现的接口那里处理
                            }
                        });
                        /**
                         * 长按监听
                         */
                        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(View v) {
                                int pos = holder.getPosition();// 得到当前点击item的位置pos
                                mListener.ItemLongClickListener(holder.itemView, pos);// 把事件交给我们实现的接口那里处理
                                return true;
                            }
                        });
                    }


                    break;

            }
        }

        @Override
        public int getItemCount() {
            return lists.size() + 1;
        }

        @Override
        public int getItemViewType(int position) {

            // 位置为0的话类型为头部，其余为内容
            return position = position == 0 ? TYPE_HEADER : TYPE_ITEM;
        }
    }


    /**
     * 内容控件的初始化
     */
    class MyViewHolderB extends RecyclerView.ViewHolder implements OnClickListener {
        public ImageView picture;
        public TextView craft;
        public TextView price;
        public TextView pingFen;
        public TextView browse;
        public TextView feature;

        public LinearLayout head;
        public LinearLayout bottom;


        public MyViewHolderB(View itemView) {
            super(itemView);
            //头部
            if (itemView.getId() == R.id.ll_find_esoterica_details_head_k_pay_front) {

                head = (LinearLayout) itemView.findViewById(R.id.ll_find_esoterica_details_head_k_pay_front);


            } else {
                picture = (ImageView) itemView.findViewById(R.id.im_item_find_esoterica_picture);
                craft = (TextView) itemView.findViewById(R.id.tv_item_find_activity_recyclerView_craft);
                pingFen = (TextView) itemView.findViewById(R.id.tv_item_find_activity_recyclerView_pingFen);
                price = (TextView) itemView.findViewById(R.id.tv_item_find_activity_recyclerView_price);
                browse = (TextView) itemView.findViewById(R.id.tv_item_find_activity_recyclerView_browse);
                feature = (TextView) itemView.findViewById(R.id.tv_item_find_activity_recyclerView_feature);
            }
        }

        @Override
        public void onClick(View v) {

        }
    }


    /**
     * 定义回调接口
     */
    interface OnItemClickListener {
        void ItemClickListener(View view, int postion);

        void ItemLongClickListener(View view, int postion);
    }


    /**
     * 获取评论
     */
    private void getHttpCommentList() {


        RequestParams params = new RequestParams();
        params.addBodyParameter("telphone", userData.getTelphone());
        params.addBodyParameter("password", userData.getPassword());
        params.addBodyParameter("id", esotericaId + "");
        params.addBodyParameter("type", 1 + "");
        params.addBodyParameter("pageIndex", 1 + "");
        params.addBodyParameter("pageSize", 1 + "");


        httpUtils.send(HttpRequest.HttpMethod.POST, HttpInterfaces.Comment_List, params, new MyRequestCallBack<String>(this, "加载中...") {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);

                    //获取列表

                    int result = json.getInt("Result");
                    if (result == 0) {
                        JSONArray data = json.getJSONArray("list");
                        commentData.addAll(JsonHelper.parseCollection(data, ArrayList.class, CommentData.class));
                        if (data.length()==0) {
                            MyToast.show(FindEsotericaDetails_K_PayFront.this, "暂不无论", 1);
                            ((TextView) findViewById(R.id.tv_find_esoterica_details_head_k_pay_front_chaKanPingLun)).setText("暂不无论");
                            return;
                        }
                        CommentData data2 = commentData.get(0);

                        bitmapUtils.display((ImageView) findViewById(R.id.im_item_comment_imageId), SystemTools.getHttpFileUrl(data2.getAvatar()));
                        ((TextView) findViewById(R.id.tv_item_comment_name)).setText(data2.getUser_name());

                        ((TextView) findViewById(R.id.tv_item_comment_describe)).setText(data2.getText());
                        ((TextView) findViewById(R.id.tv_item_comment_time)).setText(data2.getAdd_time());
                        ((TextView) findViewById(R.id.tv_item_comment_group)).setText(data2.getLikecount());


                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


}
